package server;
import java.awt.AWTException;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import action.Action;

/*thread che gestisce gli eventi in arrivo*/
public class ThreadServer extends Thread {

	private DatagramSocket sclient;							//socket con il client
	private String mex;										//messaggio ricevuto dal server, //bisogna usare StringBuilder per i noti motivi di efficienza
	private Parser parser;
	private DatagramPacket packet;
	byte[] data;


	public ThreadServer(DatagramSocket s,Parser parser) throws IOException, AWTException{
		sclient = s;
		data=new byte[1024];
		packet=new DatagramPacket(data,data.length);

		this.parser = parser;
	}

	public void run(){
		//ogni volta che mi arriva un messaggio eseguo il corpo del ciclo
		while(true){
			try {
				sclient.receive(packet);
				InetAddress destinationAddress = packet.getAddress();
				System.out.println("weeeeee");
				mex = new String(packet.getData(), 0, packet.getLength());
				// ---- PATTERN STATE ----
				Action action;
				action = parser.match(mex);
				action.execute(destinationAddress);
				// -----------------------
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
			
			
	}	
}
